package com.cykj.page05.dao.impl;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.cykj.page05.dao.IUserDao;
import com.cykj.page05.entity.StudentDO;
import com.cykj.page05.util.DruidDataSourceUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @BelongsProject: hand-tomcat
 * @BelongsPackage: com.cykj.page01.dao.impl
 * @Author: 阿隆
 * @CreateTime: 2025-11-01 11:38
 * @Description: TODO
 * @Version: 1.0
 */
public class UserDaoImpl implements IUserDao {

    @Override
    public StudentDO login(String account, String password) {

        DruidPooledConnection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {

            conn = DruidDataSourceUtils.getConn();


            //写Sql语句
            String sql = "select * from student where account = ?  and password = ?";

            //创建执行者对象
            ps = conn.prepareStatement(sql);
            ps.setString(1, account);
            ps.setString(2, password);


            //执行sql语句并处理返回结果
            rs = ps.executeQuery();

            if (rs.next()) {
                StudentDO studentDO = new StudentDO();
                studentDO.setName(rs.getString("name"));
                studentDO.setStudentId(rs.getInt("student_id"));
                return studentDO;
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            //释放资源
            DruidDataSourceUtils.releaseResource(ps, rs);

            //回收连接
            DruidDataSourceUtils.giveConn(conn);

        }

        return null;
    }

    @Override
    public Integer insertStudent(Integer stuId, String account, String password) {
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //建立连接
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/mybatis_wql",
                    "root",
                    "root");

            //写Sql语句
            String sql = "insert into student ( account , password) values (? , ?)";

            //创建执行者对象
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, account);
            ps.setString(2, password);


            //执行sql语句并处理返回结果
            int res = ps.executeUpdate();

            ps.close();
            conn.close();


            return res;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
